# == Schema Information
# Schema version: 8
#
# Table name: subscriptions
#
#  id              :integer(11)   not null, primary key
#  feed_id         :integer(11)   not null
#  user_id         :integer(11)   not null
#  category_id     :integer(11)   default(-1)
#  created_at      :datetime      not null
#  updated_at      :datetime      not null
#  display_all     :boolean(1)
#  unreadeds_count :integer(11)   default(0)
#

class Subscription < ActiveRecord::Base

  belongs_to :user
  belongs_to :feed
  belongs_to :category

  has_many :unreadeds, :dependent => :delete_all

  has_many :items, :through => :unreadeds

  validates_presence_of :feed_id, :user_id

  def self.get(user,feed)
    self.find_by_user_id_and_feed_id(user.id,feed.id)
  end

  def title
    feed.title
  end

  def link
    feed.link
  end

  def div_id
    "subscription_#{id}"
  end

  def updated_feed
    Feed.find_by_sql ["SELECT feeds.* from feeds,items,unreadeds WHERE feeds.id = items.feed_id and items.id = unreadeds.item_id and unreadeds.user_id = ? GROUP BY feeds.id", self.id]
  end

  def self.subscribe(user, feed, category_id = -1)
    subscription = Subscription.new(:feed_id => feed.id, :user_id => user.id, :category_id => category_id)
    subscription.save
    subscription.items << feed.items
    return subscription
  end

  def has_updated?
    unreadeds.size > 0
  end

  def all_item_data
    self.feed.items.map do |i|
      [i, Unreaded.get(self, i)]
    end
  end

  def unreaded_item_data
    self.unreadeds.map{ |u| [u.item, u]}
  end

  def item_data
    self.user.display_all? ? self.all_item_data : self.unreaded_item_data
  end


end
